'use client'

import { useEffect, useState } from 'react'
import { VmsCourse } from '@/types/Model'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip'
import { Input } from '@/components/ui/input'
import Link from 'next/link'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import moment from 'moment'
import { Trash2, Edit, Search, Plus, Filter, Calendar, Users, Eye, BookOpen, Share2 } from 'lucide-react'
import { toast } from '@/hooks/use-toast'
import { useRouter } from 'next/navigation'
import dynamic from 'next/dynamic'

export default function CoursesPage() {
  const [courses, setCourses] = useState<VmsCourse[]>([])
  const [filteredCourses, setFilteredCourses] = useState<VmsCourse[]>([])
  const [loading, setLoading] = useState(true)
  const [showForm, setShowForm] = useState(false)
  const [editCourse, setEditCourse] = useState<VmsCourse | null>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const router = useRouter()

  const fetchCourses = async () => {
    try {
      const token = localStorage.getItem('token')
      
      // 检查token是否存在
      if (!token) {
        router.push('/login')
        toast({
          title: '未登录',
          description: '请先登录',
          variant: 'destructive'
        })
        setCourses([])
        setFilteredCourses([])
        return
      }
      
      const response = await fetch('/api/course', {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push('/login')
          toast({
            title: '登录信息过期',
            description: '请重新登录',
            variant: 'destructive'
          })
          localStorage.clear()
        } else {
          // 处理其他错误状态码
          const errorData = await response.json().catch(() => ({ error: 'Unknown error' }))
          throw new Error(`HTTP ${response.status}: ${errorData.error || 'Server error'}`)
        }
        // 确保在所有错误情况下都设置空数组
        setCourses([])
        setFilteredCourses([])
        return
      }
      
      const data = await response.json()
      
      // 验证返回的数据格式
      if (Array.isArray(data)) {
        setCourses(data)
        setFilteredCourses(data)
        toast({
          title: '数据获取成功',
          description: '课程列表已更新',
        })
      } else {
        console.error('API returned non-array data:', data)
        setCourses([])
        setFilteredCourses([])
        toast({
          title: '数据格式错误',
          description: 'API 返回的数据格式不正确',
          variant: 'destructive'
        })
      }
    } catch (error) {
      console.error('Error fetching courses:', error)
      // 确保在错误情况下设置空数组
      setCourses([])
      setFilteredCourses([])
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  // 搜索和过滤逻辑
  useEffect(() => {
    let filtered = courses

    // 按搜索词过滤
    if (searchTerm) {
      filtered = filtered.filter(course => 
        course.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        course.description?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    }

    // 按状态过滤
    if (statusFilter !== 'all') {
      filtered = filtered.filter(course => course.status === statusFilter)
    }

    setFilteredCourses(filtered)
  }, [courses, searchTerm, statusFilter])

  useEffect(() => {
    fetchCourses()
  }, [])

  const handleDelete = async (id: string) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to delete course')
      }
      
      setCourses(prev => prev.filter(course => course.id !== id))
      toast({
        title: '删除成功',
        description: '课程已删除',
      })
    } catch (error) {
      console.error('Error deleting course:', error)
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const handleEdit = (course: VmsCourse) => {
    setEditCourse(course)
    setShowForm(true)
  }

  const handleSubmit = async (course: Partial<VmsCourse>) => {
    try {
      const token = localStorage.getItem('token')
      const method = course.id ? 'PUT' : 'POST'
      const url = course.id ? `/api/course/${course.id}` : '/api/course'
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(course)
      })
      
      if (!response.ok) {
        throw new Error(`Failed to ${course.id ? 'update' : 'create'} course`)
      }
      
      const updatedCourse = await response.json()
      
      if (course.id) {
        setCourses(prev => 
          prev.map(c => c.id === course.id ? updatedCourse : c)
        )
        toast({
          title: '更新成功',
          description: '课程已更新',
        })
      } else {
        setCourses(prev => [updatedCourse, ...prev])
        toast({
          title: '创建成功',
          description: '新课程已创建',
        })
      }
      
      setShowForm(false)
      setEditCourse(null)
    } catch (error) {
      console.error('Error submitting course:', error)
      toast({
        title: '操作失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'draft':
        return 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700'
      case 'published':
        return 'bg-green-50 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-300 dark:border-green-800'
      case 'archived':
        return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/30 dark:text-rose-300 dark:border-rose-800'
      default:
        return 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'draft': return '草稿'
      case 'published': return '已发布'
      case 'archived': return '已归档'
      default: return status
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white dark:from-slate-900 dark:to-slate-950 flex justify-center items-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-rose-600"></div>
      </div>
    )
  }

  return (
    <TooltipProvider>
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white dark:from-slate-900 dark:to-slate-950">
        <div className="container mx-auto py-8 px-4">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
              <div>
                <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-900 to-slate-700 dark:from-white dark:to-slate-300 bg-clip-text text-transparent mb-2">课程管理</h1>
                <p className="text-slate-600 dark:text-slate-400">创建和管理您的在线课程</p>
              </div>
              <Button 
                onClick={() => setShowForm(true)}
                className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white shadow-lg hover:shadow-xl transition-all duration-200 border-0"
                size="lg"
              >
                <Plus className="h-5 w-5 mr-2" />
                新建课程
              </Button>
            </div>

            {/* 搜索和过滤区域 */}
            <Card className="border-slate-200/50 dark:border-slate-800/50 shadow-sm bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm">
              <CardContent className="p-6">
                <div className="flex flex-col sm:flex-row gap-4">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 h-5 w-5" />
                    <Input
                      placeholder="搜索课程标题或描述..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-10 h-12 border-slate-200 dark:border-slate-700 focus:border-rose-500 focus:ring-rose-500 bg-white dark:bg-slate-800"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <Filter className="h-5 w-5 text-slate-400" />
                    <Select value={statusFilter} onValueChange={setStatusFilter}>
                      <SelectTrigger className="w-40 h-12 border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800">
                        <SelectValue placeholder="状态筛选" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部状态</SelectItem>
                        <SelectItem value="draft">草稿</SelectItem>
                        <SelectItem value="published">已发布</SelectItem>
                        <SelectItem value="archived">已归档</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                {/* 统计信息 */}
                <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                  <div className="flex flex-wrap gap-6 text-sm text-slate-600 dark:text-slate-400">
                    <div className="flex items-center gap-2">
                      <BookOpen className="h-4 w-4" />
                      <span>总课程: <span className="font-semibold text-slate-900 dark:text-white">{courses.length}</span></span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span>显示: <span className="font-semibold text-slate-900 dark:text-white">{filteredCourses.length}</span></span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span>已发布: <span className="font-semibold text-green-600">{courses.filter(c => c.status === 'published').length}</span></span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span>草稿: <span className="font-semibold text-slate-600">{courses.filter(c => c.status === 'draft').length}</span></span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 课程卡片网格 */}
          {filteredCourses.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-slate-400 text-lg mb-2">暂无课程</div>
              <p className="text-slate-500">创建您的第一个课程开始在线教学</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {filteredCourses.map((course) => {
                const createdDate = course.created_at ? moment(course.created_at).format('MM-DD') : 'N/A'
                const sectionCount = course.sections?.length || 0
                
                return (
                  <Card key={course.id} className="group hover:shadow-xl transition-all duration-300 border-slate-400/50 dark:border-slate-800/50 shadow-sm hover:-translate-y-1 bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm">
                    <CardHeader className="pb-3">
                      <div className="flex justify-between items-start mb-2">
                        <Badge className={`${getStatusColor(course.status)} text-xs font-medium border`}>
                          {getStatusText(course.status)}
                        </Badge>
                        <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 hover:bg-blue-50 dark:hover:bg-blue-900/30 hover:text-blue-600 dark:hover:text-blue-400"
                                onClick={() => {
                                  const shareUrl = `${window.location.origin}/course/${course.access_token}`
                                  navigator.clipboard.writeText(shareUrl)
                                  toast({
                                    title: '分享链接已复制',
                                    description: '课程分享链接已复制到剪贴板',
                                  })
                                }}
                              >
                                <Share2 className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>复制分享链接</TooltipContent>
                          </Tooltip>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 hover:bg-rose-50 dark:hover:bg-rose-900/30 hover:text-rose-600 dark:hover:text-rose-400"
                                onClick={() => handleEdit(course)}
                              >
                                <Edit className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>编辑课程</TooltipContent>
                          </Tooltip>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 hover:bg-red-50 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400"
                                onClick={async () => {
                                  const confirmWarning = window.confirm(
                                    `警告：这将永久删除课程 "${course.title}" 及其所有小节和参与者数据！\n` +
                                    '此操作不可撤销，确定要继续吗？'
                                  )
                                  
                                  if (!confirmWarning) {
                                    return
                                  }

                                  const courseName = window.prompt(`请输入课程标题 "${course.title}" 以确认删除`)
                                  if (courseName !== course.title) {
                                    toast({
                                      title: '删除取消',
                                      description: '课程标题不匹配',
                                      variant: 'destructive'
                                    })
                                    return
                                  }

                                  await handleDelete(course.id)
                                }}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>删除课程</TooltipContent>
                          </Tooltip>
                        </div>
                      </div>
                      <CardTitle className="text-lg leading-tight">
                        <Link href={`/courses/${course.id}`}>
                          <Button 
                            variant="link" 
                            className="p-0 text-left font-semibold text-lg h-auto text-slate-900 dark:text-white hover:text-rose-600 dark:hover:text-rose-400 transition-colors"
                          >
                            {course.title}
                          </Button>
                        </Link>
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4 text-sm">
                      <div className="space-y-3">
                        {course.description && (
                          <div className="flex items-start gap-2">
                            <div>
                              <p className="text-slate-600 dark:text-slate-400 leading-relaxed">
                                {course.description.length > 60 ? 
                                  `${course.description.substring(0, 60)}...` : 
                                  course.description}
                              </p>
                            </div>
                          </div>
                        )}
                        
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <Calendar className="h-4 w-4 text-slate-400" />
                            <span className="text-slate-600 dark:text-slate-400">{createdDate}</span>
                          </div>
                          <div className="flex items-center gap-4 text-xs text-slate-500">
                            <div className="flex items-center gap-1">
                              <BookOpen className="h-3 w-3" />
                              <span>{sectionCount}节</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <Users className="h-3 w-3" />
                              <span>{course.participant_count}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <Eye className="h-3 w-3" />
                              <span>{course.view_count}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )
              })}
            </div>
          )}

          {/* 表单对话框 */}
          <Dialog open={showForm} onOpenChange={(open: boolean) => {
            if (!open) {
              setShowForm(false)
              setEditCourse(null)
            }
          }}>
            <DialogContent className="sm:max-w-[600px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
              <DialogHeader>
                <DialogTitle className="text-xl font-semibold text-slate-900 dark:text-white">
                  {editCourse ? '编辑课程' : '新建课程'}
                </DialogTitle>
              </DialogHeader>
              <CourseForm 
                onCancel={() => {
                  setShowForm(false)
                  setEditCourse(null)
                }}
                onSubmit={handleSubmit}
                course={editCourse}
              />
            </DialogContent>
          </Dialog>
        </div>
      </div>
    </TooltipProvider>
  )
}

interface CourseFormProps {
  course?: VmsCourse | null
  onCancel: () => void
  onSubmit: (course: Partial<VmsCourse>) => void
}

// 动态导入 ReactQuill 以避免 SSR 问题
const ReactQuill = dynamic(() => import('react-quill'), { ssr: false })
import 'react-quill/dist/quill.snow.css'

const CourseForm = ({ course, onCancel, onSubmit }: CourseFormProps) => {
  const [formData, setFormData] = useState<Partial<VmsCourse>>({
    title: '',
    description: '',
    content_description: '',
    cover_image: '',
    is_free: true,                          // 修改：从 is_public 改为 is_free
    max_participants: undefined,            // 修改：从 '' 改为 undefined
    start_time: undefined,
    end_time: undefined,
    access_password: '',
    status: 'draft'
  })

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? (value ? Number(value) : undefined) : value
    }))
  }

  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, checked } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: checked
    }))
  }

  const handleSelectChange = (name: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit(formData)
  }

  // 新增：处理富文本编辑器内容变化
  const handleContentDescriptionChange = (content: string) => {
    setFormData(prev => ({
      ...prev,
      content_description: content
    }))
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="space-y-4">
        <div>
          <label htmlFor="title" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            课程标题 *
          </label>
          <Input
            id="title"
            name="title"
            type="text"
            value={formData.title}
            onChange={handleChange}
            className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
            placeholder="输入课程标题"
            required
          />
        </div>
        
        <div>
          <label htmlFor="description" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            课程描述
          </label>
          <textarea
            id="description"
            name="description"
            value={formData.description}
            onChange={handleChange}
            className="w-full min-h-[50px] px-3 py-2 border border-slate-200 dark:border-slate-700 rounded-md focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-rose-500 bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
            placeholder="描述课程的内容和目标"
          />
        </div>
        
        {/* 新增：课程内容简介富文本编辑器 */}
        <div>
          <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            课程内容简介（详细营销内容）
          </label>
          <div className="border border-slate-200 dark:border-slate-700 rounded-md overflow-hidden h-[250px]">
            <ReactQuill
              value={formData.content_description}
              onChange={handleContentDescriptionChange}
              placeholder="输入详细的课程营销内容，支持富文本格式"
              modules={{
                toolbar: [
                  [{ 'header': [1, 2, 3, false] }],
                  ['bold', 'italic', 'underline', 'strike'],
                  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                  [{ 'color': [] }, { 'background': [] }],
                  ['link', 'image'],
                  ['clean']
                ]
              }}
              formats={[
                'header', 'bold', 'italic', 'underline', 'strike',
                'list', 'bullet', 'color', 'background', 'link', 'image'
              ]}
              style={{
                backgroundColor: 'white',
                height: '250px'
              }}
            />
          </div>
        </div>
        
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="status" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
              课程状态
            </label>
            <Select value={formData.status} onValueChange={(value) => handleSelectChange('status', value)}>
              <SelectTrigger className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800">
                <SelectValue placeholder="选择状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="draft">草稿</SelectItem>
                <SelectItem value="published">已发布</SelectItem>
                <SelectItem value="archived">已归档</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div>
            <label htmlFor="max_participants" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
              最大参与人数
            </label>
            <Input
              id="max_participants"
              name="max_participants"
              type="number"
              value={formData.max_participants || ''}
              onChange={handleChange}
              className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
              placeholder="不限制"
              min="1"
            />
          </div>
        </div>
        
        <div>
          <label htmlFor="access_password" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            访问密码
          </label>
          <Input
            id="access_password"
            name="access_password"
            type="text"
            value={formData.access_password}
            onChange={handleChange}
            className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
            placeholder="留空表示无需密码"
          />
        </div>
        
        {/* 修改复选框标签 */}
        <div className="flex items-center space-x-2">
          <input
            type="checkbox"
            id="is_free"
            name="is_free"
            checked={formData.is_free}
            onChange={handleCheckboxChange}
            className="rounded border-gray-300"
          />
          <label htmlFor="is_free" className="text-sm font-medium">
            免费课程（学员可免费学习）
          </label>
        </div>
      </div>
      
      <div className="flex justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
        <Button 
          type="button" 
          variant="outline" 
          onClick={onCancel}
          className="border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800"
        >
          取消
        </Button>
        <Button 
          type="submit"
          className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white border-0"
        >
          {course ? '更新' : '创建'}
        </Button>
      </div>
    </form>
  )
}